package com.borqs.music.tasks;

import com.borqs.music.executor.Task;
import com.borqs.music.executor.TaskListener;
import com.borqs.music.http.HttpRequest;
import com.borqs.music.http.HttpResponse;
import com.borqs.music.http.RequestMethod;
import com.borqs.music.util.MusicConf;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class UploadFavoriteTask extends Task {
    private JSONArray mFavorJsonForSync;
    private String ticket;

    public UploadFavoriteTask(TaskListener listener, JSONArray favorJsonForSync, String ticket) {
        super(listener);
        this.ticket = ticket;
        mFavorJsonForSync = favorJsonForSync;
    }

    @Override
    public Object handleResponse(HttpResponse resp) throws Exception {
        checkResponse(resp);
        JSONArray jArr = resp.asJSONArray();
        //List<Integer> successSongids = decodeSongsJSONArray(jArr);
        return jArr; // failed update song favor state json.
    }

    @Override
    public HttpRequest prepareRequest() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("songlist", mFavorJsonForSync.toString());

        final String URL = MusicConf.getUrl(MusicConf.ReqType.MUSIC_UPDATE_LOCAL_FAVOR);
        HttpRequest request = new HttpRequest(RequestMethod.POST, URL, ticket, params);
        return request;
    }

    private List<Integer> decodeSongsJSONArray(JSONArray jArr) throws JSONException {
        List<Integer> songids = new ArrayList<Integer>(10);
        for (int i = 0, len = jArr.length(); i < len; i++) {
            JSONObject jObj;
            jObj = jArr.getJSONObject(i);
            songids.add(jObj.getInt("song_id"));
        }

        return songids;
    }

}
